package hackthon.controller;

import hackthon.core.Constant;
import hackthon.core.MyCookie;
import hackthon.core.MyRedis;
import hackthon.pojo.Email;
import hackthon.pojo.Register;
import hackthon.pojo.UserInfo;
import hackthon.service.LoginService;
import hackthon.service.RegisterService;
import hackthon.service.SendEmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by wuwenhao on 15/1/8.
 */

@Controller
public class MailRegister {

    @Autowired
    public RegisterService registerService;

    @Autowired
    public MyRedis myRedis;

    @Autowired
    public LoginService loginService;

    @Autowired
    public SendEmailService sendEmailService;



    @RequestMapping(value = "/register/{token}", method = RequestMethod.GET)
    public void index(HttpServletRequest request, HttpServletResponse response, @PathVariable String token, ModelMap map){

        try {
            PrintWriter pw = response.getWriter();
            if(!myRedis.existsKey(token)){
                pw.write("<script language=javascript>alert("+"'your link has expired'"+");window.location.href='/personCenter'"+"</script>");
                return;
            }
            String params = Constant.decodeBASE64(token);
            Cookie cookie = MyCookie.getCookie(Constant.LOGIN_COOKIE_NAME, request);
            if(cookie!=null && loginService.CookieLogin(cookie.getValue())) {
                String str[] = params.split("_");
                int emailId = Integer.parseInt(str[0]);
                String attendAddress = str[1];
                //System.out.println(emailId+attendAddress);

                Register register = registerService.getByEmailAndAttend(emailId,attendAddress);
                if(register.getStatus() == Constant.SUCCESS){
                    pw.write("<script>alert("+"'you have registered the meeting'"+");window.location.href='/personCenter'"+"</script>");
                    return;
                }

                if (registerService.ifNeedWaiting(emailId) == Constant.SUCCESS) {
                    registerService.updateRegisterStatus(emailId, attendAddress, Constant.SUCCESS);
                    pw.write("<script>alert("+"'register success'"+");window.location.href='/personCenter'"+"</script>");
                    return;

                } else if (registerService.ifNeedWaiting(emailId) == Constant.WAITING) {
                    registerService.updateRegisterStatus(emailId, attendAddress, Constant.WAITING);
                    pw.write("<script>alert("+"'register waiting'"+");window.location.href='/personCenter'"+"</script>");
                    return;
                }else{
                    registerService.updateRegisterStatus(emailId, attendAddress, Constant.REJECTED);
                    pw.write("<script>alert("+"'register rejected'"+");window.location.href='/personCenter'"+"</script>");
                    return;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @RequestMapping("/personCenter")
    public String personCenter(HttpServletRequest request, HttpServletResponse response, ModelMap map){
        Cookie cookie = MyCookie.getCookie(Constant.LOGIN_COOKIE_NAME, request);
        if(cookie!=null && loginService.CookieLogin(cookie.getValue())) {
            String str[] = Constant.decodeBASE64(cookie.getValue()).split("_");
            String username = str[0];
            System.out.println(username);
            UserInfo userInfo = loginService.getUserByUserName(username);
            String attendAddress = userInfo.getEmail();
            //System.out.println(emailId+attendAddress);

            try {
                List list = registerService.getCurrentEmailList(attendAddress);

                List mailList = new ArrayList();
                Iterator iterator = list.iterator();
                while (iterator.hasNext()) {
                    int activeEmailId = ((Register) iterator.next()).getEmailId();
                    mailList.add(sendEmailService.getEmailById(activeEmailId));
                }
                map.addAttribute("mailInfo", mailList);
                map.addAttribute("statusInfo", list);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "Personal";
        }else{
            return "redirect:/login.jsp";
        }
    }

    @RequestMapping(value = "/unregister/{token}", method = RequestMethod.GET)
    public void unregister(HttpServletRequest request, HttpServletResponse response, @PathVariable String token){
        String params = Constant.decodeBASE64(token);
        String str[] = params.split("_");
        int emailId = Integer.parseInt(str[0]);
        String attendAddress = str[1];
        registerService.updateRegisterStatus(emailId, attendAddress,Constant.REJECTED);
        try {
            PrintWriter printWriter = response.getWriter();
            printWriter.write("<script>alert("+"'unregister successfully'"+");window.location.href='/personCenter'"+"</script>");
            return;
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
